<script setup>
//数据引入及依赖引入模块
import { useRoute, useRouter } from 'vue-router'
import { reactive, ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue';
const $route = useRoute();
const $router = useRouter()
import { events } from '../../bus/bus.js'
import Data from "@/tool.json"
const tool = reactive(Data)
import axios from "axios"

//天气卡片模块
const temperatureNow = ref()
const typeNow = ref()
const qualityNow = ref()
const cityNow = ref()
const weatherCard = ref("background-image:url(../rainy.png)")
fetch("/weather/api/weather/city/101300505", {//不同城市是有不同citykey的，通过获取citykey表加使用浏览器获取定位实现
    method: "GET",
})
.then(res => res.json())
.then(res => {
    temperatureNow.value = res.data.wendu
    typeNow.value = res.data.forecast[1].type
    switch (typeNow.value) {
        case "晴":
            weatherCard.value = "background-image:url(../sunny.png)"
            break;
        case "阴","多云":
            weatherCard.value = "background-image:url(../cloudy.png)"
            break;
        default:
            weatherCard.value = "background-image:url(../rainy.png)"
                break;
    }
    qualityNow.value = res.data.quality
    cityNow.value = res.cityInfo.parent
})
const humidityNow = ref("")
const temperatureRoomNow = ref("")
const roomNameNow = ref("")
const roomBasicInfo = reactive([])
let roomList = []
let arrayRes = []
//配对房间名和窗帘温湿度信息
const searchRoomInfo = (res) => {
    for (let i = 0; i < arrayRes.length; i++) {
        for (let j = 0; j < roomList.length; j++) {
            for (let k = 0; k < roomList[j].deviceList.length; k++) {
                if (arrayRes[i] == roomList[j].deviceList[k].sadder) {
                    if (res[arrayRes[i]].humidity != null || res[arrayRes[i]].temperature != null) {
                        roomBasicInfo.push({ 'name': roomList[j].name,'humidity':res[arrayRes[i]].humidity,'temperature':res[arrayRes[i]].temperature})
                    }
                }
            }
        }
    }
}
const changRoomTime = ref(0)
const changeRoomShow = () => {
    if (changRoomTime.value == roomBasicInfo.length) { changRoomTime.value = 0 }
    roomNameNow.value = roomBasicInfo[changRoomTime.value].name;
    humidityNow.value = roomBasicInfo[changRoomTime.value].humidity;
    temperatureRoomNow.value = roomBasicInfo[changRoomTime.value].temperature;
}
const cardRequest = axios.create({
    baseURL: 'api',
    timeout: 3000,
    withCredentials: true,
});
cardRequest.post("/room", {
    type: "getRoomList"
}).then(
    (res) => {
        roomList = res.data.roomList;
        fetch("/api/getProperties", {
            method: "GET"
        })
            .then(res => res.json())
            .then(res => {
                arrayRes = Object.keys(res)
                searchRoomInfo(res)
                changeRoomShow()
            })
    }
)


//设备添加模块
const rollIcon = ref("transform: rotate(0turn)");
let rollIsp = 0;
const addShow = ref("right:0;opacity: 0;visibility: hidden;")
const showAddDevices = () => {
    rollIsp++;
    rollIcon.value = "transform: rotate(" + 0.125 * rollIsp + "turn)";
    rollIsp % 2 == 0 ? addShow.value = "right:0;opacity: 0;visibility: hidden;" : addShow.value = "right:21vw;opacity: 1;visibility: visiable;";
}

//设备房间切换模块
const deviceFontChange = ref("color:#bf7130");
const roomFontChange = ref("color:#fef4e8");
const inchoosestyle = ref("left:-5vw")
const roomOrDevice = ref(0)
const changeMode = (val) => {
    switch (val) {
        case 'device':
            deviceFontChange.value = "color:#bf7130";
            roomFontChange.value = "color:#fef4e8";
            inchoosestyle.value = "left:-5vw";
            roomOrDevice.value = 0
            break;
        case 'room':
            deviceFontChange.value = "color:#fef4e8";
            roomFontChange.value = "color:#bf7130";
            inchoosestyle.value = "left:40vw";
            roomOrDevice.value = 1
            break;
    }
}

//住址名称模块
const homeName = ref('房屋名称')//暂存本地，后端忘记这part了,@blur了一个setItem
homeName.value = localStorage.getItem('homeName')? localStorage.getItem('homeName'):'获取失败'
const setItem = () => {
    localStorage.setItem('homeName', homeName.value)
}

//全局bus传输点击设备类型模块（mitt失效，先用localstorage存着）
const deviceBus = (val) => {
    localStorage.setItem("deviceType", JSON.stringify(val));
}
const routerlink = () => {
    if (roomOrDevice.value == 0) $router.push({ name: "device" })
    else if(roomOrDevice.value == 1) $router.push({ name: "room" })
}

//设备列表渲染模块
const deviceTotal = reactive([])
const dataFormat = (res) => { //添加设备大类名称及大类下的小设备id、名称、大类名称、短地址
    console.log(res);
    if (deviceTotal.length == 0) {
        deviceTotal.push({ 'name': res[0].productName, 'equipment': [] })
    }
    for (let i = 0; i < res.length; i++) {
        for (let j = 0; j < deviceTotal.length; j++) {
            if (res[i].productName == deviceTotal[j].name) { break }
            else if( j == deviceTotal.length-1 ){
                deviceTotal.push({ 'name': res[i].productName, 'equipment': [] })
                break;
            }
        }
    }
    for (let i = 0; i < res.length; i++) {
        for (let j = 0; j < deviceTotal.length; j++) {
            if (res[i].productName == deviceTotal[j].name) {
                deviceTotal[j].equipment.push({ deviceId: res[i].deviceId ,deviceName: res[i].name, productName: res[i].productName,sadder:res[i].sadder })
            }
        }
    }
}

const twiceDataFormat = (respon) => {//添加小设备对应的房间
    for (let i = 0; i < deviceTotal.length; i++) {
        for (let j = 0; j < deviceTotal[i].equipment.length; j++){
            deviceTotal[i].equipment[j].room = "未知房间"
        }
    }
    for (let i = 0; i < deviceTotal.length; i++){
        for (let j = 0; j < deviceTotal[i].equipment.length; j++)
            for (let k = 0; k < respon.length; k++) {
                for (let z = 0; z < respon[k].deviceList.length; z++) {
                    if (respon[k].deviceList[z].deviceId == deviceTotal[i].equipment[j].deviceId) {
                        deviceTotal[i].equipment[j].room = respon[k].name;
                    }
                }
            }
    }
}

const thirdthDataFormat = (res) => {//添加小设备对应的属性
    console.log(res,deviceTotal);
    for (let j = 0; j < deviceTotal.length; j++) {
        for (let k = 0; k < deviceTotal[j].equipment.length; k++){
            if (res[deviceTotal[j].equipment[k].sadder] != undefined) {
                deviceTotal[j].equipment[k].brightness = res[deviceTotal[j].equipment[k].sadder].brightness
                deviceTotal[j].equipment[k].humidity = res[deviceTotal[j].equipment[k].sadder].humidity
                deviceTotal[j].equipment[k].left = res[deviceTotal[j].equipment[k].sadder].left
                deviceTotal[j].equipment[k].right = res[deviceTotal[j].equipment[k].sadder].right
                deviceTotal[j].equipment[k].temperature = res[deviceTotal[j].equipment[k].sadder].temperature
                deviceTotal[j].equipment[k].lockState = res[deviceTotal[j].equipment[k].sadder].lockState
            }
        }
    }
}

const forthDataFormat = () => {//格式小设备对应的属性
    for (let j = 0; j < deviceTotal.length; j++) {
        for (let k = 0; k < deviceTotal[j].equipment.length; k++) {
            if (deviceTotal[j].equipment[k].brightness != null) {
                for (let i = 0; i < deviceTotal[j].equipment[k].brightness.length; i += 2) {
                    switch (i) {
                        case 0:
                            deviceTotal[j].equipment[k].firstLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 2:
                            deviceTotal[j].equipment[k].secondLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 4:
                            deviceTotal[j].equipment[k].thirdLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        case 6:
                            deviceTotal[j].equipment[k].forthLight = parseInt(deviceTotal[j].equipment[k].brightness[i]) * 16 + parseInt(deviceTotal[j].equipment[k].brightness[i + 1])
                            break;
                        default:
                            break;
                    }
                }
                if (deviceTotal[j].equipment[k].brightness == "00000000") {
                    deviceTotal[j].equipment[k].status = 0
                } else {
                    deviceTotal[j].equipment[k].status = 1
                }
            } else if ((deviceTotal[j].equipment[k].left != null) && (deviceTotal[j].equipment[k].right != null)) {
                if ((deviceTotal[j].equipment[k].left == 100) && (deviceTotal[j].equipment[k].right == 100)) {//反向判断，窗帘100反而是关上
                    deviceTotal[j].equipment[k].status = 1
                } else {
                    deviceTotal[j].equipment[k].status = 0
                }
            } else if (deviceTotal[j].equipment[k].productName == "网关") {
                deviceTotal[j].equipment[k].status = 1
            } else if (deviceTotal[j].equipment[k].lockState != null) {
                if (deviceTotal[j].equipment[k].lockState == "00") {
                    deviceTotal[j].equipment[k].status = 0
                } else {
                    deviceTotal[j].equipment[k].status = 1
                }
            }
        }
    }
}

//卡片icon模块
const iconSet = (name) => {
    switch (name) {
        case "灯控":
            return "\ue856"
        case "智能窗帘":
            return "\ue605"
        case "智能门锁":
            return "\ue625"
        case "网关":
            return "\uec5d"
    }
}

//设备switch模块 ,接收switch的开和关,在获取后端数据后进行修改
const switchChange = (val, indexOfTool, indexOfEquipment, name, sadder) => {
    if (val) {
        deviceTotal[indexOfTool].equipment[indexOfEquipment].status = 0;
        switch (name) {
            case "灯控":
                cardRequest.post("/message", [{
                    'saddr': String(sadder.slice(0, 2) + ' ' + sadder.slice(2, 4)),
                    "dcode": "01",
                    "rdata": "00 00 00"
                }])
                break;
            case "智能窗帘":
                cardRequest.post("/message", [{
                    'saddr': String(sadder.slice(0, 2) + ' ' + sadder.slice(2, 4)),
                    "dcode": "02",
                    "rdata": "00 00"
                }])
                break;
            case "智能门锁":
            case "网关":
        }
    } else {
        deviceTotal[indexOfTool].equipment[indexOfEquipment].status = 1;
        switch (name) {
            case "灯控":
                cardRequest.post("/message", [{
                    'saddr': String(sadder.slice(0, 2) + ' ' + sadder.slice(2, 4)),
                    "dcode": "01",
                    "rdata": "00 00 64"
                }])
                break;
            case "智能窗帘":
                cardRequest.post("/message", [{
                    'saddr': String(sadder.slice(0, 2) + ' ' + sadder.slice(2, 4)),
                    "dcode": "02",
                    "rdata": "00 64"
                }])
                break;
            case "智能门锁":
            case "网关":
        }
    }
    roomFormat(roomTotal)
}

fetch("/api/getEndDeviceList ", {
    method: "GET",
})
    .then(res => res.json())
    .then(res => {
        dataFormat(res)
        cardRequest.post("/room", {
            type: "getRoomList"
        }).then((respon) => {
            twiceDataFormat(respon.data.roomList)
            fetch("/api/getProperties ", {
                method: "GET",
            })
                .then(r => r.json())
                .then(r => {
                    thirdthDataFormat(r)
                    forthDataFormat()
                })
        })
    })

//房间列表渲染模块 
const roomTotal = reactive([])
const roomFormat = (res) => { //添加设备大类名称及大类下的小设备id、名称、大类名称、短地址
    roomTotal.push(...res);
    for (let i = 0; i < roomTotal.length; i++){
        for (let j = 0; j < roomTotal[i].deviceList.length; j++){
            for (let k = 0; k < deviceTotal.length; k++){
                for (let p = 0; p < deviceTotal[k].equipment.length; p++){
                    if (roomTotal[i].deviceList[j].deviceId == deviceTotal[k].equipment[p].deviceId) {
                        setTimeout(() => {
                             roomTotal[i].deviceList[j].status = deviceTotal[k].equipment[p].status
                        }, 500);
                    }
                }
            }
        }
    }
}

//房间switch样式模块,接收switch的开和关,在获取后端数据后进行修改
const switchChangeOfRoom = (val, indexOfTool, indexOfEquipment) => {
    if (val) {
        roomTotal[indexOfTool].deviceList[indexOfEquipment].status = 0;

    } else {
        roomTotal[indexOfTool].deviceList[indexOfEquipment].status = 1;
    }
    for (let i = 0; i < deviceTotal.length; i++){
        for (let j = 0; j < deviceTotal[i].equipment.length; j++){
            if (deviceTotal[i].equipment[j].deviceId == roomTotal[indexOfTool].deviceList[indexOfEquipment].deviceId) {
                deviceTotal[i].equipment[j].status = roomTotal[indexOfTool].deviceList[indexOfEquipment].status
            }
        }
    }
}
cardRequest.post("/room", {
    type: "getRoomList"
}).then((res) => {
    roomFormat(res.data.roomList)
})

console.log(deviceTotal);
</script>

<template>
  <body class="w-[100vw] h-[100vh] select-none">
    <header class="h-[5rem] w-full flex justify-between items-center">
        <h1 class="text-[#c77430] border-l-8 border-[#ffbf40] pl-[.5rem] ml-[1rem]">
            <input type="text" v-model="homeName" class="bg-transparent focus:outline-none" @blur="setItem()">
        </h1>
        <add class="absolute bg-[#ffd073] text-[#e29c45] w-1/2 h-[2.4rem] rounded-full flex items-center transition-all duration-220 ease-in-out overflow-hidden" :style="addShow">
            <addDevice class="w-1/2 h-full flex items-center justify-center border-r-2 hover:bg-[#ffad51]">添加设备</addDevice>
            <addRoom class="w-1/2 h-full flex items-center justify-center hover:bg-[#ffad51]"  @click="$router.push({ name: 'addroom' })">添加房间</addRoom>
        </add>
        <icon @click="showAddDevices" class="transition-all duration-220 ease-in-out mr-[1rem]" :style="rollIcon"><i class="iconfont text-[#ffbf40]">&#xe642;</i></icon>
    </header>
    <main class="w-full h-auto flex flex-col items-center">
        <card class="w-5/6 h-[9rem] bg-[#f0f0f0] rounded-xl flex flex-col mb-[1rem] bg-cover bg-no-repeat bg-center " :style="weatherCard">
            <weather class="w-full h-1/2 flex justify-between">
                <temperature class="ml-[1.5rem] mt-[1rem] flex items-center">
                    <num class="text-[2.5rem] font-bold text-[#ffffff] opacity-60">
                        {{ temperatureNow }}
                    </num>
                    <text class="flex flex-col justify-center h-full text-[#ffffff] opacity-60">
                        <icon>℃</icon>
                        <text>{{ typeNow }}</text>
                    </text>
                </temperature>
                <location class="flex flex-col justify-center items-center mr-[1.5rem] mt-[1rem]">
                    <text class="text-[#ffffff] opacity-60">{{ "空气污染：" + qualityNow }}</text>
                    <position class="w-full flex items-cente justify-end">
                        <i class="iconfont text-[#ffffff] opacity-60 pr-[.2rem]" style="font-size: 16px;">&#xe613;</i>
                        <text class="text-[.8rem] flex items-center justify-center text-[#ffffff] opacity-60">{{ cityNow }}</text>
                    </position>
                </location>
            </weather>
            <sensors class="h-1/2 w-full flex justify-between items-center text-[#b0b0b0]">
                <room class="ml-[1.5rem]">
                    <text @click="changRoomTime++, changeRoomShow()" class="text-[1.3rem] font-bold border-l-4 border-[#b0b0b0] pl-[.5rem] text-[#ffffff] opacity-60">{{ roomNameNow? roomNameNow:"获取失败" }}</text>
                </room>
                <sensors class="text-[#ffffff] opacity-60">
                    温度:<text class="text-[1.2rem] ">{{ temperatureRoomNow? temperatureRoomNow:"获取失败" }}</text>℃
                </sensors>
                <sensors class="mr-[1.5rem] text-[#ffffff] opacity-60">
                    湿度:<text class="text-[1.2rem] ">{{ humidityNow? humidityNow:"获取失败" }}</text>%
                </sensors>
            </sensors>
        </card>
        <operation class="w-full h-auto flex flex-col items-center">
            <choose class="relative w-5/6 h-[2.2rem] text-[#bf7130] bg-[#ffd073] rounded-2xl flex" style="box-shadow:inset 0 2px 4px #cca65c">
                <choose @click="changeMode('device')" class="w-1/2 h-full rounded-2xl flex justify-center items-center z-10 transition-all duration-220 ease-in-out" :style="deviceFontChange">设备</choose>
                <choose @click="changeMode('room')" class="w-1/2 h-full rounded-2xl flex justify-center items-center z-10 transition-all duration-220 ease-in-out" :style="roomFontChange">房间</choose>
                <inchoose class="absolute w-3/5 h-[2.4rem] bg-gradient-to-r from-[#ffe259] to-[#ffa751] rounded-2xl top-[-.1rem] transition-all duration-220 ease-in-out" :style="inchoosestyle"></inchoose>
            </choose>
            <!-- 设备页面 -->
            <card v-if="!roomOrDevice" class="w-full h-[50vh] flex justify-center items-center flex-wrap pt-[1rem] overflow-auto">
                <item v-for="(item,indexOfTool) in deviceTotal" :key="item" class="w-[20rem] h-[7rem]  mx-[.5rem] mb-[1rem] rounded-xl flex items-center overflow-hidden">
                    <name @click="deviceBus(item.name), routerlink()" class="flex flex-col w-[30%] h-full pl-[1.2rem] bg-[#ffc773] text-[#e29c45] border-2 border-[#cc9f5c] rounded-l-xl">
                        <icon class="w-[2.5rem] h-[2.5rem] rounded-2xl  my-[.5rem] flex items-center justify-center">
                            <i class="iconfont" style="font-size: 2rem;">{{ iconSet(item.name) }}</i>
                        </icon>
                        <text class="font-bold">{{ item.name }}</text>
                        <text class="text-[.8rem]">
                            设备数:
                            <text class="text-[1.2rem] font-bold">{{ item.equipment.length }}</text>
                        </text>
                    </name>
                    <div class="w-[1px] h-full bg-[#cc9f5c]"></div>
                    <status class="w-[70%] h-[90%] flex flex-wrap justify-start my-[.5rem] pr-[.5rem] overflow-auto bg-[#fed6a7] rounded-r-2xl" style="box-shadow:inset 2px 0px 4px #cc9f5c;">
                        <block v-for="(i,indexOfEquipment) in item.equipment" :key="i" class="flex w-full h-[2rem] justify-between items-center my-[0.75rem] text-[#e29c45]">
                            <div class="flex flex-col w-[8rem] items-center">
                                <text class="text-[1.1rem] font-bold w-[8rem] overflow-hidden drop-shadow flex justify-center">{{ i.deviceName }}</text>
                                <text class="text-[.8rem]">{{'#' + i.room + '#'}}</text>
                            </div>
                            <switch @click="switchChange(i.status,indexOfTool,indexOfEquipment,item.name,i.sadder)" class="w-[5.5rem] h-full rounded-2xl flex relative justify-end items-center transition-all duration-220 ease-in-out" :style="i.status?'background-color:#7bcfa6;box-shadow:inset 0 2px 4px #5c9c7d':'background-color:#f05654;box-shadow:inset 0 2px 4px #bd4342'">
                                <point class="absolute h-[1.8rem] w-[1.8rem] rounded-full bg-gradient-to-r from-[#ffe259] to-[#ffa751] top-[0.08rem] transition-all duration-220 ease-in-out" :style="i.status?'left:0.1rem;box-shadow: 0 2px 4px #725e82':'left:3.55rem;box-shadow: 0 2px 4px #725e82'"></point>
                            </switch>
                        </block>
                    </status>
                </item>
            </card>
            <!-- 房间页面 -->
            <card v-if="roomOrDevice" class="w-full h-[50vh] flex justify-center items-center flex-wrap pt-[1rem] overflow-auto">
                    <item v-for="(item, indexOfTool) in roomTotal" :key="item" class="w-[20rem] h-[7rem]  mx-[.5rem] mb-[1rem] rounded-xl flex items-center overflow-hidden">
                        <name @click="deviceBus(item.name), routerlink()" class="flex flex-col w-[30%] h-full pl-[1.2rem] bg-[#ffc773] text-[#e29c45] border-2 border-[#cc9f5c] rounded-l-xl justify-center">
                            <text class="font-bold text-[1.2rem]">{{ item.name }}</text>
                            <text class="text-[.8rem]">
                                设备数:
                                <text class="text-[1rem] font-bold">{{ item.deviceList.length }}</text>
                            </text>
                        </name>
                        <div class="w-[1px] h-full bg-[#cc9f5c]"></div>
                        <status class="w-[70%] h-[90%] flex flex-wrap justify-start my-[.5rem] pr-[.5rem] overflow-auto bg-[#fed6a7] rounded-r-2xl" style="box-shadow:inset 2px 0px 4px #cc9f5c;">
                            <block v-for="(i, indexOfEquipment) in item.deviceList" :key="i" class="flex w-full h-[2rem] justify-between items-center my-[0.75rem] text-[#e29c45]">
                                <div class="flex flex-col w-[8rem] items-center">
                                    <text class="text-[1.1rem] font-bold w-[8rem] overflow-hidden drop-shadow flex justify-center">{{ i.name }}</text>
                                    <text class="text-[.8rem]">{{ '#' + i.productName + '#' }}</text>
                                </div>
                                <switch @click="switchChangeOfRoom(i.status, indexOfTool, indexOfEquipment)" class="w-[5.5rem] h-full rounded-2xl flex relative justify-end items-center transition-all duration-220 ease-in-out" :style="i.status?'background-color:#7bcfa6;box-shadow:inset 0 2px 4px #5c9c7d':'background-color:#f05654;box-shadow:inset 0 2px 4px #bd4342'">
                                    <point class="absolute h-[1.8rem] w-[1.8rem] rounded-full bg-gradient-to-r from-[#ffe259] to-[#ffa751] top-[0.08rem] transition-all duration-220 ease-in-out" :style="i.status?'left:0.1rem;box-shadow: 0 2px 4px #725e82':'left:3.55rem;box-shadow: 0 2px 4px #725e82'"></point>
                                </switch>
                            </block>
                        </status>
                    </item>
                </card>
        </operation>
    </main>
  </body>
</template>

<style>
@font-face {
  font-family: 'iconfont';  /* Project id 4312277 */
  src: url('//at.alicdn.com/t/c/font_4312277_hdfqowl1seb.woff2?t=1705413352628') format('woff2'),
       url('//at.alicdn.com/t/c/font_4312277_hdfqowl1seb.woff?t=1705413352628') format('woff'),
       url('//at.alicdn.com/t/c/font_4312277_hdfqowl1seb.ttf?t=1705413352628') format('truetype');
}
.iconfont{
    font-family:"iconfont" !important;
    font-size:24px;
    font-style:normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
}
</style>